package mspbots.qbd.desktop.core.customers;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.log4j.Log4j2;
import mspbots.qbd.common.RabbitKeys;
import mspbots.qbd.desktop.core.BaseGenericService;
import org.json.JSONObject;
import org.json.XML;
import org.springframework.stereotype.Service;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.StringWriter;

/**
 * CustomersService
 *
 * @author <a href="https://github.com/vnobo">Alex bob</a>
 * @date Created by 2020/9/14
 */
@Log4j2
@Service
public class CustomersService extends BaseGenericService {

    public void sendCustomers(NodeList nodeList, Long tenantId) {
        for (int temp = 0; temp < nodeList.getLength(); temp++) {
            Node node = nodeList.item(temp);
            NodeList el = ((Element) node).getElementsByTagName("ListID");
            String listId = el.item(0).getTextContent();
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                String content = this.nodeToString(node);
                JSONObject jsonObject = XML.toJSONObject(content);
                ObjectNode objectNode = super.objectMapper.createObjectNode();
                try {
                    objectNode = super.objectMapper.readValue(jsonObject.get("CustomerRet").toString(), ObjectNode.class);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
                objectNode.put("tenantId", tenantId);
                objectNode.put("ListID", listId);
                this.messagingTemplate.convertAndSend(RabbitKeys.BASE_EXCHANGE_NAME,
                        RabbitKeys.CUSTOMERS_SYNC_QUEUE_KEY, objectNode);
            }
        }
    }

    private String nodeToString(Node node) {
        StringWriter sw = new StringWriter();
        try {
            Transformer t = TransformerFactory.newInstance().newTransformer();
            t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            t.setOutputProperty(OutputKeys.INDENT, "yes");
            t.transform(new DOMSource(node), new StreamResult(sw));
        } catch (TransformerException te) {
            System.out.println("nodeToString Transformer Exception");
        }
        return sw.toString();
    }
}
